<?php

namespace app\api\controller\mycurrency;

use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use app\common\model\mycurrency\AgentApply;
use app\common\model\mycurrency\AgentConfig;
use app\common\model\mycurrency\AgentInformation;
use app\common\model\mycurrency\AgentMoneylog;
use app\common\model\mycurrency\AgentMoneyWithdrawal;
use app\common\model\mycurrency\AgentProfit;
use fast\Random;
use think\Config;
use think\Exception;
use think\Validate;
use think\Db;

/**
 * 代理商接口
 */
class Agent extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = '*';
    protected $agent = null;

    protected $verificationIdentity = ['applyfor'];//不验证是否是代理商

    public function _initialize()
    {
        parent::_initialize();
        if (!$this->auth->match($this->verificationIdentity)) {
            $agent = \app\common\model\mycurrency\Agent::where(['user_id' => $this->auth->id,'deletetime' => null])->find();
            if(!$agent){
                $this->error('还未成为代理商');
            }
            if($agent['status'] == \app\common\model\mycurrency\Agent::STATUS_JINYONG){
                $this->error('代理商已被禁用');
            }
            $this->agent = $agent;
        }
    }

    /**
     * 代理商申请
     */
    public function applyfor(){
        $param = $this->request->param();

        $rule = [
            ['is_identity', "require|in:1,2", ['代理商身份不能为空','身份类型错误']],
        ];
        $check = $this->validate($param, $rule);
        if ($check !== true) {
            $this->error($check);
        }
        if ($param['is_identity'] == \app\common\model\mycurrency\Agent::IS_IDENTITY_GEREN){//个人申请
            $rule = [
                ['fullname', 'require', '姓名不能为空'],
                ['gender', 'require', '性别不能为空'],
                ['age', 'require', '年龄不能为空'],
                ['idnumber', 'require', '身份证号不能为空'],
                ['phone', ['require','/^1[3-9]\d{9}$/'], ['手机号不能为空','手机号格式不正确']],
                ['wechat_number', 'require', '微信号不能为空'],
                ['mailbox', 'require', '邮箱不能为空'],
                ['intention_city_id', 'require', '意向城市不能为空'],
                ['intention_hospital', 'require', '意向医院不能为空'],
                ['idnumber_just_image', 'require', '身份证正面不能为空'],
                ['idnumber_back_image', 'require', '身份证反面不能为空'],
            ];
            $check = $this->validate($param, $rule);
            if ($check !== true) {
                $this->error($check);
            }
        }elseif ($param['is_identity'] == \app\common\model\mycurrency\Agent::IS_IDENTITY_QIYE){//企业申请
            $rule = [
                ['coprorate_name', 'require', '公司名称不能为空'],
                ['coprorate_code', 'require', '公司代码不能为空'],
                ['bus_address', 'require', '经营地址不能为空'],
                ['duty_paragraph', 'require', '税票号不能为空'],
                ['duty_coprorate_name', 'require', '税票号公司名称不能为空'],
                ['opening_bank', 'require', '开户行不能为空'],
                ['corporate_account', 'require', '对公账号不能为空'],
                ['license_image', 'require', '营业执照不能为空'],
                ['permit_image', 'require', '开户许可不能为空'],
                ['qualifications_images', 'require', '资质证明不能为空'],
            ];
            $check = $this->validate($param, $rule);
            if ($check !== true) {
                $this->error($check);
            }
        }

        $agent_apply = AgentApply::where(['user_id' => $this->auth->id,'deletetime' => null])->find();
        if($agent_apply){
            if($agent_apply['status'] == AgentApply::STATUS_DAICHULI){
                $this->error('代理申请中，请勿重复提交申请');
            }
            if($agent_apply['status'] == AgentApply::STATUS_YITONGGUO){
                $this->error('已成为代理商');
            }
        }
        Db::startTrans();
        try {
            $increase = [
                'is_identity' => $param['is_identity'],
                'user_id' => $this->auth->id,
                'fullname' => $param['fullname'],
                'phone' => $param['phone'],
                'status' => AgentApply::STATUS_DAICHULI,
                'applytime' => time(),
                'createtime' => time(),
            ];
            $apply = AgentApply::create($increase);

            $information_increase = [
                'agent_apply_id' => $apply->id,
                'createtime' => time()
            ];
            if ($param['is_identity'] == \app\common\model\mycurrency\Agent::IS_IDENTITY_GEREN){//个人申请
                $information_increase['fullname'] = $param['fullname'];
                $information_increase['gender'] = $param['gender'];
                $information_increase['age'] = $param['age'];
                $information_increase['idnumber'] = $param['idnumber'];
                $information_increase['phone'] = $param['phone'];
                $information_increase['wechat_number'] = $param['wechat_number'];
                $information_increase['mailbox'] = $param['mailbox'];
                $information_increase['intention_city_id'] = $param['intention_city_id'];
                $information_increase['intention_hospital'] = $param['intention_hospital'];
                $information_increase['idnumber_just_image'] = $param['idnumber_just_image'];
                $information_increase['idnumber_back_image'] = $param['idnumber_back_image'];
            }elseif ($param['is_identity'] == \app\common\model\mycurrency\Agent::IS_IDENTITY_QIYE){//企业申请
                $information_increase['coprorate_name'] = $param['coprorate_name'];
                $information_increase['coprorate_code'] = $param['coprorate_code'];
                $information_increase['bus_address'] = $param['bus_address'];
                $information_increase['duty_paragraph'] = $param['duty_paragraph'];
                $information_increase['duty_coprorate_name'] = $param['duty_coprorate_name'];
                $information_increase['opening_bank'] = $param['opening_bank'];
                $information_increase['corporate_account'] = $param['corporate_account'];
                $information_increase['license_image'] = $param['license_image'];
                $information_increase['permit_image'] = $param['permit_image'];
                $information_increase['qualifications_images'] = $param['qualifications_images'];
            }
            AgentInformation::create($information_increase);
            Db::commit();
        } catch (Exception $e){
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('申请成功');
    }


    /**
     * 代理商详情
     */
    public function agentinfo(){
        $details = \app\common\model\mycurrency\Agent::where(['id' => $this->agent->id])->field('id,number,fullname,phone,money')->find();

        //默认查询条件
        $where = ['agent_id' => $this->agent->id,'deletetime' => null];

        //今日时间戳
        $todayTime =  strtotime(date("Y-m-d 00:00:00")).','.strtotime(date("Y-m-d 23:59:59"));

        //本周开始 及本周 结束时间戳
        $startTimestamp = strtotime("this week Monday");
        $endTimestamp = strtotime("this week Sunday") + 86400 - 1;
        $circumTime = $startTimestamp.','.$endTimestamp;

        //本月开始 及本月 结束时间戳
        $firstDayOfMonth = strtotime(date('Y-m-01 00:00:00'));
        $lastDayOfMonth = strtotime(date('Y-m-t 23:59:59'));
        $themoonTime = $firstDayOfMonth . ',' . $lastDayOfMonth;
        $statistics = [
            'profit_total' => AgentProfit::where($where)->sum('actual_income'),//总计收益
            'profit_canreflect' => $details['money'],//可提现收益
            'profit_today' => AgentProfit::where($where)->where(['createtime' => ['between',$todayTime]])->sum('actual_income'),//今日收益
            'profit_thisweek' => AgentProfit::where($where)->where(['createtime' => ['between',$circumTime]])->sum('actual_income'),//本周收益
            'profit_thismonth'=> AgentProfit::where($where)->where(['createtime' => ['between',$themoonTime]])->sum('actual_income'),//本月收益
        ];
        $this->success('',[
            'details' => $details,
            'statistics' => $statistics,
        ]);
    }

    /**
     * 代理商余额变动记录
     */
    public function moneyLog(){
        $params = $this->request->param();
        $rule = [
            ['page', 'require', '页码不能为空'],
            ['pageSize', 'require', '每页查询条数不能为空'],
        ];
        $check = $this->validate($params, $rule);
        if ($check !== true) {
            $this->error($check);
        }

        $where = [
            'agent_id' => $this->agent->id,
        ];

        $list = AgentMoneylog::where($where)
            ->limit(($params['page'] - 1) * $params['pageSize'], $params['pageSize'])
            ->order('id desc')
            ->field('id,money,memo,type,createtime')
            ->select();
        foreach($list as $k => $v){
            if($list[$k]['type'] == AgentMoneylog::TYPE_HOUTAIJIANSHAO || $list[$k]['type'] == AgentMoneylog::TYPE_TIXIAN){//
                $list[$k]['money'] = '-' . $list[$k]['money'];
            }

        }
        $num = AgentMoneylog::where($where)->count();
        if ($num > $params['page'] * $params['pageSize']) {
            $nextpage = true;
        } else {
            $nextpage = false;
        }
        $this->success('获取成功', ['list' => $list, 'nextpage' => $nextpage]);
    }

    /**
     * 代理商收益记录
     */
    public function profitList(){
        $params = $this->request->param();
        $rule = [
            ['page', 'require', '页码不能为空'],
            ['pageSize', 'require', '每页查询条数不能为空'],
        ];
        $check = $this->validate($params, $rule);
        if ($check !== true) {
            $this->error($check);
        }
        $where = [
            'agent_id' => $this->agent->id,
        ];
        $list = AgentProfit::where($where)
            ->limit(($params['page'] - 1) * $params['pageSize'], $params['pageSize'])
            ->order('id desc')
            ->field('id,tra_amount,div_proportion,actual_income,memo,createtime')
            ->select();
        $num = AgentProfit::where($where)->count();
        if ($num > $params['page'] * $params['pageSize']) {
            $nextpage = true;
        } else {
            $nextpage = false;
        }
        $this->success('获取成功', ['list' => $list, 'nextpage' => $nextpage]);
    }


    /**
     * 代理商申请提现
     */
    public function withdrawal(){
        $param = $this->request->param();
        $rule = [
            ['money', 'require|>:0', '提现金额不能为空|提现金额必须是大于0的数字'],
            ['payment_mode', 'require', '提现方式不能为空'],
        ];
        $check = $this->validate($param, $rule);
        if ($check !== true) {
            $this->error($check);
        }
        if($param['payment_mode'] == AgentMoneyWithdrawal::PAYMENT_MODE_XIANXIA){//打款方式为线下打款
            if (!array_key_exists('bank_number',$param) || !$param['bank_number'] ||
                !array_key_exists('bank_opening',$param) || !$param['bank_opening'] ||
                !array_key_exists('bank_account',$param) ||!$param['bank_account']){
                throw new Exception('银行卡信息不完善');
                return false;
            }
        }elseif ($param['payment_mode']  == AgentMoneyWithdrawal::PAYMENT_MODE_WEIXINSHOUKUANMA){//提现方式:4=微信收款码收款
            if (!array_key_exists('wechat_code_image',$param) ||!$param['wechat_code_image']){
                throw new Exception('微信收款码不能为空');
                return false;
            }
        }elseif ($param['payment_mode']  == AgentMoneyWithdrawal::PAYMENT_MODE_ZHIFUBAOSHOUKUANMA){//提现方式:5=支付宝收款码收款
            if (!array_key_exists('alipay_code_image',$param) ||!$param['alipay_code_image']){
                throw new Exception('支付宝收款吗不能为空');
                return false;
            }
        }
        $agent_config = AgentConfig::where(['id' => 1])->field('shareratio,witserpro,minwit_amount')->find();
        if($param['money'] < $agent_config['minwit_amount']){
            $this->error("体现金额不得小于:{$agent_config['minwit_amount']}元");
        }
        Db::startTrans();
        try {
            $agent = \app\common\model\mycurrency\Agent::where(['id' => $this->agent->id])->find();//->lock(true)
            if($agent->money < $param['money']){
                throw new Exception('余额不足');
            }
            $service_charge = number_format(( $param['money'] / 100 ) * $agent_config['witserpro'],2,'.','') ;//手续费
            $actual_payment = $param['money'] - $service_charge;//实际需要打款金额
            $increase = [
                'agent_id' => $agent['id'],
                'money' => $param['money'],
                'witserpro' => $agent_config['witserpro'],
                'service_charge' => $service_charge,
                'actual_payment' => $actual_payment,
                'payment_mode' => $param['payment_mode'],
                'explain' => $param['explain'],
                'status' => AgentMoneyWithdrawal::STATUS_DAICHULI,
                'applytime' => time(),
                'createtime' => time(),
                'bank_number' => $param['bank_number'],
                'bank_opening' => $param['bank_opening'],
                'bank_account' => $param['bank_account'],
            ];
            $withdrawal = AgentMoneyWithdrawal::create($increase);
            /**
             * 处理余额变动
             * @param int $agent_id 代理商ID
             * @param int $money 变动金额
             * @param  int $type 变动类型
             * @param array $data 数据
             */
            AgentMoneylog::moneyChange($agent['id'],$param['money'],AgentMoneylog::TYPE_TIXIAN,[
                'memo' => '代理商申请提现',
                'withdrawal_id' => $withdrawal->id,
            ]);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('申请提现成功');
    }

    /**
     * 代理商申请提现记录
     */
    public function withdrawalLog(){
        $params = $this->request->param();
        $rule = [
            ['page', 'require', '页码不能为空'],
            ['pageSize', 'require', '每页查询条数不能为空'],
        ];
        $check = $this->validate($params, $rule);
        if ($check !== true) {
            $this->error($check);
        }

        $where = [
            'agent_id' => $this->agent->id,
        ];

        $list = AgentMoneyWithdrawal::where($where)
            ->limit(($params['page'] - 1) * $params['pageSize'], $params['pageSize'])
            ->order('id desc')
            ->field('*')
            ->select();
        foreach($list as $k => $v){

        }
        $num = AgentMoneyWithdrawal::where($where)->count();
        if ($num > $params['page'] * $params['pageSize']) {
            $nextpage = true;
        } else {
            $nextpage = false;
        }
        $this->success('获取成功', ['list' => $list, 'nextpage' => $nextpage]);
    }


}
